import Vue from 'vue'
import VueRouter from 'vue-router'
import HomeView from '../views/Home/index.vue'
import store from "@/store"
import { getUserInfo } from '@/utils/utils'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: 'home',
  },
  {
    path: '/home',
    name: 'home',
    component: HomeView,
    meta: {
      title: '首页',
    }
  },
  {
    path: '/allProducts',
    name: 'allProducts',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "allProducts" */ '../views/AllProducts.vue'),
    meta: {
      title: '全部商品',
    }
  },
  {
    path: '/productDetail',
    name: 'productDetail',
    component: () => import(/* webpackChunkName: "productDetail" */ '../views/ProductDetail.vue'),
    meta: {
      title: '商品详情',
    }
  },
  {
    path: '/personCenter',
    name: 'personCenter',
    component: () => import(/* webpackChunkName: "personCenter" */ '../views/PersonCenter.vue'),
    meta: {
      title: '个人中心',
    }
  },
  {
    path: '/myOrder',
    name: 'myOrder',
    component: () => import(/* webpackChunkName: "myOrder" */ '../views/MyOrder.vue'),
    meta: {
      title: '我的订单',
    }
  },
  {
    path: '/welfare',
    name: 'welfare',
    component: () => import(/* webpackChunkName: "welfare" */ '../views/Welfare.vue'),
    meta: {
      title: '专属福利',
    }
  },
]

// 解决即将加载的路由与当前路由重复时的报错
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function (location) {
  // console.log(this); // 原型对象中的方法 this 指向 调用它的实例对象；
  originalPush.call(this, location).catch((err) => {
    // console.log(err);
  });
};

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

// 全局路由前置守卫，页面刷新或者是路由跳转都会被拦截到
router.beforeEach((to, from, next) => {

  // 如果发现vuex中个人信息为空丢失了，那么重新发送请求获取最新的用户数据
  // 正常的路由跳转不会使vuex数据初始化，只有页面刷新重新加载才会使vuex数据初始化！！！
  if (localStorage.getItem('token') && !store.state.user.userInfo) {
    // 发送请求
    console.log('@获取个人信息')
    getUserInfo();
  }
  next();
})

export default router
